package listbyorder.access101_200.test138;

import java.util.HashMap;
import java.util.Map;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/6/11 11:17
 */
public class Solution1 {

    // 辅助带随机指针的链表
    // 字节写的方法，超时
    public Node copyRandomList(Node head) {
        if (head == null) return head;

        Map<Integer, Node> map = new HashMap<>();

        map.put(head.val, new Node(head.val));
        Node temp = head;

        while (temp != null) {
            if (temp.next != null) {
                if (!map.containsKey(temp.next.val)) {
                    map.put(temp.next.val, new Node(temp.next.val));
                }
            }
            if (temp.random != null) {
                if (!map.containsKey(temp.random.val)) {
                    map.put(temp.random.val, new Node(temp.random.val));
                }
            }
            temp = temp.next;
        }

        temp = head;
        while (temp != null) {
            if (temp.next != null) {
                map.get(temp.val).next = map.get(temp.next.val);
            }
            if (temp.random != null) {
                map.get(temp.val).random = map.get(temp.random.val);
            }
            temp = temp.next;
        }

        return map.get(head.val);
    }
}
